import {Component, OnDestroy, OnInit} from '@angular/core';
import {ExtendHttpService} from "../../common/extend-http.service";
import {TipService} from "../services/tip.service";
import {ActivatedRoute, Router} from "@angular/router";
import {IndexService} from "../services/index.service";
import {Subscription} from "rxjs";

declare let layer;

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit, OnDestroy {

  subscribeData:Subscription;

  // 菜品分类列表
  foodClassList = [];

  // 根据分类取到的菜品列表
  foodList = [];

  // 是否查看菜品大图
  showBigPic: any = false;
  bigImgUrl: any = '';

  // 当前选中的分类
  selectClass = null;

  // 购物车是否显示状态
  shoppingShow = false;

  // 按规格选菜时的显示状态
  standardDialogShow = false;

  // 按规格当前操作的菜品
  foodItem = {};

  // 搜索显示状态
  searchState = true;

  // 右侧下拉列表状态
  rightSpinnerState = false;

  // 加菜订单id, 加菜时头部桌台变为退出，选桌变为下单
  addFood = {
    addOrderId: '',
    tableClass: '',
    tableName: '',
    tableId: ''
  }

  tipType = 'error';

  constructor(private extendHttp: ExtendHttpService,
              private tipService: TipService,
              private router: Router,
              private indexService: IndexService,
              private activatedRoute: ActivatedRoute) {
    this.activatedRoute.queryParams.subscribe(param => {
      if (param && param['addOrderId']) {
        // 加菜时清除购物车数据
        this.indexService.clearData();
        this.addFood.addOrderId = param['addOrderId'];
        this.searchState = !this.searchState;
      }
    });
  }

  goSearch() {
    this.router.navigate(['/main/search'],{queryParams: {addOrderId: this.addFood.addOrderId}});
  }

propertyOp(arr) {
    arr.forEach((v, k) => {
      v.count = 0;
      if (!this.selectClass) {
        if (k === 0) {
          this.selectClass = v;
          this.foodList = v.foodList;
        }
      }
      let count = 0;
      v.foodList.forEach((v1, k1) => {
        count += v1.count;
      });
      v.count = count;
    });

    this.foodClassList = arr;
  }

  ngOnInit() {

    cBack =()=> {
      $('#btn-back').trigger('click');
    }
    // 进入页面订阅数据
    this.subscribeData = this.indexService.foodAllEmit.subscribe(res => {
      this.propertyOp(res);
    });

    // 没有数据获取数据
    if (!this.foodClassList.length) {
      this.propertyOp(this.indexService.getData());
    }

    if (this.addFood['addOrderId']) {
      this.getTableNames(this.addFood['addOrderId']);
    }

  }

  // 根据订单id获取餐桌名称
  getTableNames(orderId) {
    this.extendHttp.post('/merchantApp/singleprocess/getTableClass', {orderId: orderId}).subscribe(response => {
      let data = response.json();
      if (data.code == '0') {
        this.addFood.tableClass = data.tableClassName;
        this.addFood.tableName = data.tableName;
        this.addFood.tableId = data.tableId;
      } else if (data.code == '-2001') {
        this.tipService.change(true, '登录超时，跳转到登录页面');
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 2000);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, data.message);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

  // 加菜时退出的操作
  addQuit() {
    this.addFood.addOrderId = '';
    this.addFood.tableClass = '';
    this.addFood.tableName = '';
    this.searchState = !this.searchState;
  }

  // 加菜时搜索切换
  changeSearch() {
    this.searchState = !this.searchState;
  }

  // 点击图片查看菜品大图
  openImg(v) {
    let url = v.figure_url;
    this.showBigPic = true;
    this.bigImgUrl = url;
  }

  /* ---------------------------------------------------------- 按规格操作开始 ---------------------------------------------------------------------- */
  standard(item) {
    this.standardDialogShow = true;
    this.foodItem = item;
    // console.log(this.foodItem)
  }

  standardShowHide($event) {
    this.standardDialogShow = $event;
  }

  maskShowHide($event) {
    this.standardDialogShow = $event;
  }

  /* ---------------------------------------------------------- 按规格操作结束 ---------------------------------------------------------------------- */

  // 加菜
  add(item) {

    item.count++;
    this.selectClass['count']++;
    this.indexService.updateData(this.foodClassList);
  }

  //减菜
  reduce(item) {
    if (item.count > 0) {
      item.count--;
      this.selectClass['count']--;
      this.indexService.updateData(this.foodClassList);
    }
  }

  // 自定义数量
  modifyCount(v) {
    let ocount = v.count;
    let unit = v.unit ? v.unit : '份';
    let modifyOpen = layer.open({
      type: 1,
      title: '自定义数量',
      btn: ['确定'],
      // shadeClose: true,
      content: '<div style="padding: 20px;">' +
      '<input type="number" style="border: 1px solid #eee;height: 38px;" id="modifiedCount" value="' + ocount + '">' +
      '<label style="font-weight: 600;"> ' + unit + '</label>' +
      '</div>',
      icon: 1,
      area: ['', ''],
      offset: ['25%', ''],
      yes: () => {
        v.count = $('#modifiedCount').val() * 1;
        this.selectClass.count = v.count;
        this.indexService.updateData(this.foodClassList);

        layer.close(modifyOpen);
      },
      cancel: function () {
        // layer.msg('关闭');
      }
    });
  }

  // 菜品分类点击事件
  classChange(v) {
    this.selectClass = v;
    this.foodList = v.foodList;
  }

  /* ---------------------------------------------------------- 购物车操作开始 ---------------------------------------------------------------------- */

  // 点击购物车图标是否打开购物车列表
  shopNavChange($event) {
    if (typeof $event === "boolean") {
      this.shoppingShow = $event;
    }
  }

  // 点击遮罩关闭
  maskChange($event) {
    this.shoppingShow = $event;
  }

  // 购物车列表没有数据时，关闭
  shopListChange($event) {
    this.shoppingShow = $event;
  }

  /* ---------------------------------------------------------- 购物车操作结束 ---------------------------------------------------------------------- */


  /* ---------------------------------------------------------- 右侧下拉列表操作开始 ---------------------------------------------------------------------- */

  changeRightSpinnerState() {
    this.rightSpinnerState = !this.rightSpinnerState;
  }


  /* ---------------------------------------------------------- 右侧下拉列表操作结束 ---------------------------------------------------------------------- */


  ngOnDestroy() {
    this.subscribeData.unsubscribe();
  }

}
